package cn.waxcc.service.impl;

import cn.waxcc.pojo.Commodity;
import cn.waxcc.pojo.ResponseResult;
import cn.waxcc.service.CommodityService;
import cn.waxcc.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

import static cn.waxcc.utils.RedisConstant.OVERALL_SHOPPING_COMMODITY;
import static cn.waxcc.utils.RedisConstant.SHOPPING_COMMODITY;

/**
 * @author: zhangJiaQing
 * @createDate: 2023/4/23 16:59
 * @description: go for it! just do it!
 */
@Service
@RequiredArgsConstructor
public class CommodityServiceImpl implements CommodityService {

    private final RedisUtil redisUtil;

    @Override
    public ResponseResult getCommodityService() {
        Map<String, Commodity> cacheMap = redisUtil.getCacheMap(OVERALL_SHOPPING_COMMODITY);
        //数量
        int size = cacheMap.size();
        //价格
        Integer price = 0;
//        cacheMap.forEach((key,value)->{ map遍历方式一
//            System.out.println(key);
//            System.out.println(value);
//        });
        //map遍历方式二
        Iterator<Map.Entry<String, Commodity>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Commodity> entry = iterator.next();
            Commodity value = entry.getValue();
            if (value.getPitchOn()) {
                price += Integer.valueOf(value.getPrice());
            }
        }
        return new ResponseResult(200, cacheMap, size, price.toString());
    }

    @Override
    public ResponseResult addCommodityService(Commodity commodity) {
        if (Objects.isNull(commodity)) {
            return new ResponseResult(500, "参数不能为空");
        }
        redisUtil.setCacheMapValue(OVERALL_SHOPPING_COMMODITY, SHOPPING_COMMODITY + commodity.getId(), commodity);
        return new ResponseResult(200, "添加成功");
    }

    @Override
    public ResponseResult putCommodityService(Commodity commodity) {
        if (Objects.isNull(commodity)) {
            return new ResponseResult(500, "参数不能为空");
        }
        redisUtil.setCacheMapValue(OVERALL_SHOPPING_COMMODITY, SHOPPING_COMMODITY + commodity.getId(), commodity);
        return new ResponseResult(200, "修改成功!");
    }

    @Override
    public ResponseResult deleteCommodityService() {
        boolean b = redisUtil.deleteObject(OVERALL_SHOPPING_COMMODITY);
        if(b){
            return new ResponseResult(200, "删除成功!");
        }
        return new ResponseResult(500, "删除失败!");
    }
}
